<template>
  <div class="app-container">
    <el-form
      ref="datasetForm"
      :model="datasetForm"
      :rules="rules"
      label-width="100px"
      class="dataset-form"
    >
      <el-form-item label="数据集ID" prop="datasetId">
        <el-input
          v-model="datasetForm.datasetId"
          disabled
        />
      </el-form-item>
      <el-form-item label="数据集名称" prop="datasetName">
        <el-input
          v-model="datasetForm.datasetName"
          placeholder="请输入数据集名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="数据集编码" prop="datasetCode">
        <el-input
          v-model="datasetForm.datasetCode"
          disabled
        />
      </el-form-item>
      <el-form-item label="数据集类型" prop="datasetType">
        <el-select
          v-model="datasetForm.datasetType"
          disabled
        >
          <el-option
            v-for="item in datasetTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据源" prop="datasourceId">
        <el-select
          v-model="datasetForm.datasourceId"
          placeholder="请选择数据源"
          @change="handleDatasourceChange"
          :disabled="!isNewDataSource"
        >
          <el-option
            v-for="item in datasourceOptions"
            :key="item.datasourceId"
            :label="item.datasourceName"
            :value="item.datasourceId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据源编码" prop="datasourceCode">
        <el-input
          v-model="datasetForm.datasourceCode"
          disabled
        />
      </el-form-item>
      <el-form-item label="数据源名称" prop="datasourceName">
        <el-input
          v-model="datasetForm.datasourceName"
          disabled
        />
      </el-form-item>
      <el-form-item
        label="数据集定义"
        prop="datasetDefinition"
        :rules="getDefinitionRules"
      >
        <el-input
          v-model="datasetForm.datasetDefinition"
          :placeholder="getDefinitionPlaceholder"
          :rows="isQueryType ? 8 : 1"
          :type="isQueryType ? 'textarea' : 'text'"
          :show-word-limit="!isQueryType"
          :maxlength="!isQueryType ? 500 : undefined"
        />
        <div class="definition-tips" v-if="isQueryType">
          <el-alert
            title="SQL语句要求"
            type="info"
            description="请输入有效的SELECT查询语句，系统会自动限制查询数量以保护性能。"
            show-icon
            :closable="false"
          />
        </div>
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input
          v-model="datasetForm.version"
          disabled
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="datasetForm.status">
          <el-radio label="0">启用</el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="datasetForm.remark"
          placeholder="请输入备注信息"
          maxlength="500"
          show-word-limit
          type="textarea"
          rows="3"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleTestConnection">
          测试连接
        </el-button>
        <el-button type="success" @click="handleSubmit" :loading="submitting">
          提交
        </el-button>
        <el-button @click="handleCancel">
          取消
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 测试连接结果对话框 -->
    <el-dialog
      title="测试连接结果"
      :visible.sync="testResultVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="test-result-container">
        <div v-if="testResult.success" class="test-success">
          <i class="el-icon-success"></i>
          <div class="test-message">{{ testResult.message }}</div>
          <div class="test-details">
            <div class="detail-item">
              <span class="detail-label">列数：</span>
              <span class="detail-value">{{ testResult.columnCount }}</span>
            </div>
            <div class="detail-title">列信息：</div>
            <el-table
              :data="testResult.columns"
              border
              style="width: 100%"
              size="small"
            >
              <el-table-column prop="name" label="列名" width="150" />
              <el-table-column prop="type" label="数据类型" width="150" />
              <el-table-column prop="displayName" label="显示名称" />
            </el-table>
          </div>
        </div>
        <div v-else class="test-error">
          <i class="el-icon-error"></i>
          <div class="test-message">{{ testResult.message }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDatasetById, updateDataset, getDatasourceList, getDatasetTypeList, testDatasetConnection } from "@/api/system/dataset";

// 移除 Element Plus 图标导入

export default {
  name: "EditDataset",
  components: {
    // 移除组件注册
  },
  data() {
    return {
      // 表单加载状态
      submitting: false,
      loading: true,
      // 数据集表单
      datasetForm: {
        datasetId: null,
        datasetName: "",
        datasetCode: "",
        datasetType: "",
        datasourceId: "",
        datasourceCode: "",
        datasourceName: "",
        datasetDefinition: "",
        version: "",
        status: "0",
        remark: ""
      },
      // 验证规则
      rules: {
        datasetName: [
          { required: true, message: "请输入数据集名称", trigger: "blur" },
          { min: 1, max: 100, message: "数据集名称长度不能超过100个字符", trigger: "blur" }
        ],
        datasetType: [
          { required: true, message: "请选择数据集类型", trigger: "change" }
        ],
        datasourceId: [
          { required: true, message: "请选择数据源", trigger: "change" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ]
      },
      // 数据源选项
      datasourceOptions: [],
      // 数据集类型选项
      datasetTypeOptions: [],
      // 测试连接结果对话框
      testResultVisible: false,
      // 测试连接结果
      testResult: {
        success: false,
        message: "",
        columnCount: 0,
        columns: []
      },
      // 是否可以更换数据源（根据系统配置决定）
      isNewDataSource: false
    };
  },
  created() {
    // 检查是否允许更换数据源（这里可以根据系统配置决定）
    this.isNewDataSource = true; // 暂时允许更换数据源
    this.init();
  },
  computed: {
    // 是否为查询类型
    isQueryType() {
      return this.datasetForm.datasetType === "query";
    },
    // 根据数据集类型获取定义提示文本
    getDefinitionPlaceholder() {
      switch (this.datasetForm.datasetType) {
        case "table":
          return "请输入表名";
        case "view":
          return "请输入视图名";
        case "query":
          return "请输入SQL查询语句";
        default:
          return "请输入数据集定义";
      }
    },
    // 根据数据集类型获取定义验证规则
    getDefinitionRules() {
      const baseRule = [{ required: true, message: "请输入数据集定义", trigger: "blur" }];

      if (this.isQueryType) {
        // SQL查询类型特殊验证
        return [
          ...baseRule,
          { validator: this.validateQueryDefinition, trigger: "blur" }
        ];
      }

      return baseRule;
    }
  },
  methods: {
    // 初始化
    init() {
      const datasetId = this.$route.params.datasetId;
      if (datasetId) {
        this.getDatasetDetail(datasetId);
      } else {
        this.loading = false;
        this.$modal.msgError("参数错误，未找到数据集ID");
        this.handleCancel();
      }

      // 获取数据源列表
      getDatasourceList().then(response => {
        this.datasourceOptions = response.data;
      });

      // 获取数据集类型列表
      getDatasetTypeList().then(response => {
        this.datasetTypeOptions = response.data;
      });
    },
    // 获取数据集详情
    getDatasetDetail(datasetId) {
      getDatasetById(datasetId)
        .then(response => {
          if (response.code === 200) {
            // 确保从后端获取的数据正确赋值，特别是datasetType字段
            const data = response.data || {};
            this.datasetForm = {
              ...this.datasetForm,
              ...data,
              // 确保datasetType不为空
              datasetType: data.datasetType || ''
            };

            // 打印调试信息，检查datasetType是否正确设置
            console.log('数据集详情加载完成，datasetType:', this.datasetForm.datasetType);
          } else {
            this.$modal.msgError(response.msg || "获取数据集详情失败");
            this.handleCancel();
          }
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
          this.$modal.msgError("获取数据集详情失败: " + (error.message || "未知错误"));
          this.handleCancel();
        });
    },
    // 数据源变更
    handleDatasourceChange() {
      if (this.datasetForm.datasourceId) {
        const datasource = this.datasourceOptions.find(item => item.datasourceId === this.datasetForm.datasourceId);
        if (datasource) {
          this.datasetForm.datasourceCode = datasource.datasourceCode;
          this.datasetForm.datasourceName = datasource.datasourceName;
        }
      } else {
        this.datasetForm.datasourceCode = "";
        this.datasetForm.datasourceName = "";
      }
    },
    // SQL查询定义验证器
    validateQueryDefinition(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入SQL查询语句"));
      } else {
        // 简单验证是否以SELECT开头
        const trimmedValue = value.trim().toUpperCase();
        if (!trimmedValue.startsWith("SELECT")) {
          callback(new Error("SQL查询语句必须以SELECT开头"));
        } else {
          callback();
        }
      }
    },
    // 测试连接
    handleTestConnection() {
      this.$refs.datasetForm.validate(valid => {
        if (valid) {
          // 准备测试数据
          const testData = {
            datasourceCode: this.datasetForm.datasourceCode,
            datasetType: this.datasetForm.datasetType,
            datasetDefinition: this.datasetForm.datasetDefinition
          };

          this.testResult = { success: false, message: "正在测试连接...", columnCount: 0, columns: [] };
          this.testResultVisible = true;

          // 调用测试接口
          testDatasetConnection(testData)
            .then(response => {
              if (response.code === 200) {
                this.testResult = {
                  success: true,
                  message: "测试成功",
                  columnCount: response.data.columnCount || 0,
                  columns: response.data.columns || []
                };
              } else {
                this.testResult = {
                  success: false,
                  message: response.msg || "测试失败",
                  columnCount: 0,
                  columns: []
                };
              }
            })
            .catch(error => {
              this.testResult = {
                success: false,
                message: error.message || "测试失败，请检查网络或服务",
                columnCount: 0,
                columns: []
              };
            });
        }
      });
    },
    // 提交表单
    handleSubmit() {
      this.$refs.datasetForm.validate(valid => {
        if (valid) {
          this.submitting = true;

          // 确保datasetType不为空
          if (!this.datasetForm.datasetType) {
            this.submitting = false;
            this.$modal.msgError("数据集类型不能为空");
            return;
          }

          // 创建一个新对象，确保所有必要字段都被正确传递
          const submitData = {
            ...this.datasetForm
          };

          updateDataset(submitData)
            .then(response => {
              this.submitting = false;

              if (response.code === 200) {
                this.$modal.msgSuccess("修改数据集成功");
                this.handleCancel();
              } else {
                this.$modal.msgError(response.msg || "修改数据集失败");
              }
            })
            .catch(error => {
              this.submitting = false;
              this.$modal.msgError("修改数据集失败: " + (error.message || "未知错误"));
            });
        }
      });
    },
    // 取消
    handleCancel() {
      this.$router.push("/data/dataset");
    }
  }
};
</script>

<style scoped>
.dataset-form {
  max-width: 800px;
}

.definition-tips {
  margin-top: 10px;
}

.test-result-container {
  padding: 20px;
  text-align: center;
}

.test-success,
.test-error {
  padding: 20px;
}

.success-icon,
.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.test-message {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.test-details {
  text-align: left;
  margin-top: 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.detail-label {
  font-weight: bold;
  margin-right: 10px;
}

.detail-title {
  font-weight: bold;
  margin: 15px 0 10px 0;
}
</style>
